package com.example.myandroidapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.ScrollView
import androidx.appcompat.widget.AppCompatButton
import com.google.android.material.floatingactionbutton.FloatingActionButton

class ScrollView_Component : AppCompatActivity() {

    private lateinit var scrollView: ScrollView
    private lateinit var backToTopButton: FloatingActionButton

    // 定义滚动阈值，超过这个距离显示回到顶部按钮
    private val SCROLL_THRESHOLD = 300

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scroll_view_component)

        // 初始化视图
        scrollView = findViewById(R.id.scrollView)
        backToTopButton = findViewById(R.id.backToTopButton)

        // 设置滚动监听器
        scrollView.viewTreeObserver.addOnScrollChangedListener {
            val scrollY = scrollView.scrollY

            // 当滚动距离超过阈值时显示按钮，否则隐藏
            if (scrollY > SCROLL_THRESHOLD) {
                if (backToTopButton.visibility == android.view.View.GONE) {
                    backToTopButton.show()
                }
            } else {
                if (backToTopButton.visibility == android.view.View.VISIBLE) {
                    backToTopButton.hide()
                }
            }
        }

        // 设置回到顶部按钮点击事件
        backToTopButton.setOnClickListener {
            // 平滑滚动到顶部
            scrollView.smoothScrollTo(0, 0)
        }
    }
}